package com.jhc.controller;


import com.jhc.bo.UserSaveDetails;
import com.jhc.dto.BizCheckMessageDto;
import com.jhc.dto.BizNoticeSearchDto;
import com.jhc.dto.CheckNoticeAddDto;
import com.jhc.entity.CmsNoticeObject;
import com.jhc.server.WebSocketServer;
import com.jhc.service.IBacNoticeObjectService;
import com.jhc.service.IBacNoticeService;
import com.jhc.utils.CommonResult;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 业务消息表  前端控制器
 * </p>
 *
 * @author zfm
 * @since 2019-11-24
 */
@RestController
@RequestMapping("/notice")
@Api(tags = "消息业务")
public class CmsNoticeController {
    @Autowired
    private IBacNoticeService iBacNoticeService;
    @Autowired
    private IBacNoticeObjectService iBacNoticeObjectService;
    @Autowired
    private UserSaveDetails userSaveDetails;

    @PostMapping("/send")
    public CommonResult sendMessage(@RequestBody CheckNoticeAddDto checkNoticeAddDto) {
        List<BizCheckMessageDto> bizCheckMessageDtoList = iBacNoticeService.sendMessage(checkNoticeAddDto);
        if (bizCheckMessageDtoList == null) {
            return CommonResult.failed("发送失败");
        }
        bizCheckMessageDtoList.forEach(item -> {
            try {
                WebSocketServer.sendInfo(CommonResult.success(item), item.getUserNumber());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        return CommonResult.success("发送成功");
    }

    /**
     * 阅读消息
     *
     * @param id
     * @return
     */
    @PatchMapping("/{id}")
    public CommonResult readMessage(@PathVariable Long id) {
        CmsNoticeObject cmsNoticeObject = new CmsNoticeObject();
        cmsNoticeObject.setId(id);
        cmsNoticeObject.setIsRead(true);
        cmsNoticeObject.setReadTime(new Date());
        if (iBacNoticeObjectService.updateById(cmsNoticeObject)) {
            return CommonResult.success("已读成功");
        }
        return CommonResult.failed("消息不存在");
    }

    /**
     * 普通用户查询消息
     *
     * @param bizNoticeSearchDto
     * @return
     */
    @GetMapping("/my")
    public CommonResult getMessageByMy(BizNoticeSearchDto bizNoticeSearchDto) {
        String username = userSaveDetails.getCmsUser().getNumber();
        return CommonResult.success(iBacNoticeObjectService.selectByUsername(bizNoticeSearchDto, username));
    }

    /**
     * 管理员用户查询消息
     *
     * @param bizNoticeSearchDto
     * @return
     */
    @GetMapping("/admin")
    public CommonResult getMessageByAdmin(BizNoticeSearchDto bizNoticeSearchDto) {
        return CommonResult.success(iBacNoticeObjectService.selectByUsername(bizNoticeSearchDto, null));
    }
}
